<?php

namespace Admin\Models\res;

use Admin\Models\BaseModel;
use Admin\Models\app\XhappStore;
use Helpers\HttpClient;
use Helpers\Tool;
use Helpers\Main;
class XhresQuestionbankcontact extends BaseModel
{

    /**
     *
     * @var integer
     */
    public $iQBCId;

    /**
     *
     * @var string
     */
    public $iAppCode;

    /**
     *
     * @var integer
     */
    public $iSchoolId;

    /**
     *
     * @var integer
     */
    public $iQBankId;

    /**
     *
     * @var integer
     */
    public $iOrderCode;

    /**
     *
     * @var integer
     */
    public $bDelete;

    /**
     *
     * @var string
     */
    public $tCreateDate;

    /**
     *
     * @var string
     */
    public $iCreateUserId;

    /**
     *
     * @var string
     */
    public $tLastModifyDate;

    /**
     *
     * @var string
     */
    public $iLastModifyUserId;

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        parent::initialize();
        $this->setSource("XHRes_QuestionBankContact");
    }

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'XHRes_QuestionBankContact';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhresQuestionbankcontact[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return XhresQuestionbankcontact
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * 创建新model并载入信息后返回
     *
     * @param $data
     * @return XhresQuestionbankcontact
     *
     * create by ck 20160924
     */
    public static function createRecord($data)
    {
        $obj = new self;
        $obj->assign($data);
        return $obj;
    }

    /**
     * 根据学校ID，应用编号，题库ID找出相应记录并返回
     *
     * @param $schoolId
     * @param $appCode
     * @param $ids
     * @return XhresQuestionbankcontact[]
     *
     * create by ck 20160924
     */
    public static function getRecordByAppCodeSchoolQBankId($schoolId, $appCode, $ids)
    {
        return  self::find(array(
            'conditions' => "bDelete = 0 AND iSchoolId = {$schoolId} AND iAppCode = '{$appCode}' AND iQBankId IN ({$ids})"
        ));
    }

    /**
     * 根据题库ID获取已关联的应用编号，并遍历应用编号对书架进行刷新
     *
     * @param $qBankId      --题库ID
     * @return bool
     *
     * create by ck 20160909
     * modify by ck 20171218    --刷新语文基础知识书库
     */
    public static function refreshBookshelfByQuestionBankId($qBankId)
    {
        $appCode = self::find(array(
            'columns'       => 'iAppCode',
            'conditions'    => 'bDelete = 0 AND iQBankId = :iQBankId:',
            'group'         => 'iAppCode',
            'bind'          => array(
                'iQBankId'      => $qBankId
            )
        ));
        if(!$appCode) return false;
        $appCode = $appCode->toArray();
        $appCodeArr = array_column($appCode, 'iAppCode');
        foreach($appCodeArr as $appCode) {
            Main::refreshBookshelf($appCode, 'all');
            if (in_array($appCode, ['1300'])) {
                $config = Main::getConfigByName($appCode);
                if (!$config) {
                    continue;
                }
                $httpClient = new HttpClient($config['url']);
                $response = $httpClient->get($config['refreshBook'], ['bookid' => $qBankId]);
                Main::createCommitLog('res', 'QuestionBank', 'pack', $response, $qBankId, '刷新应用');
            }
        }
    }

    /**
     * 删除应用时如无编号则删除题库并刷新书架
     *
     * @param $appCodeArr
     * @return bool
     *
     * create by ck 20161020
     */
    public static function deleteRecordByAppCode($appCodeArr)
    {
        //查找应用编号数组下未删除的信息（应用编号一样的情况）
        $existAppCode = XhappStore::find([
            'columns'    => 'iAppCode',
            'conditions' => 'bDelete = 0 AND bAppHistory = 0 AND iAppCode IN ({codeArr:array})',
            'bind'       => [
                'codeArr'   => $appCodeArr
            ]
        ])->toArray();
        $existAppCode = array_column($existAppCode, 'iAppCode');

        //求差集并删除，如无差集则直接返回true
        $appCodeArr = array_diff($appCodeArr, $existAppCode);
        if(!$appCodeArr) return true;
        $result = self::find([
            'conditions'    => 'bDelete = 0 AND iAppCode IN ({codeArr:array})',
            'bind'          => [
                'codeArr'       => $appCodeArr
            ]
        ])->delete();
        if(!$result) return false;
        foreach($appCodeArr as $appCode){
            Main::refreshBookshelf($appCode, 'all');
        }
        return true;
    }

}
